package top.kent90.controller;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.kent90.common.controller.BaseController;
import top.kent90.common.object.LoginObject;
import top.kent90.common.util.MD5Util;
import top.kent90.common.util.VerifyCode;
import top.kent90.pojo.SysUser;
import top.kent90.service.LoginService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("login")
public class LoginController extends BaseController {

    //通过dubbo服务提供bean注入(idea报红，不用管)
    @Reference
    LoginService loginService;

    @RequestMapping("doLogin")
    public String doLogin(String loginName, String loginPassword, String verifyCode,
                          HttpServletRequest request, Model model) {

        //后端校验，手机号和密码为空情况放前台校验
        System.out.println("----------进入校验流程-----------");

        Object obj = request.getSession().getAttribute("verifyCode");
        if(obj==null) {
            model.addAttribute("msg", "会话超时，请重新登录!");
            return "../../index";
        }
        String sessionVerifyCode = (String)obj;
        //4  验证码错误
        if(!sessionVerifyCode.equalsIgnoreCase(verifyCode)) {
            model.addAttribute("msg", "验证码错误!");
            //数据带回
            model.addAttribute("loginName", loginName);
            model.addAttribute("loginPassword", loginPassword);
            return "../../index";
        }

        //开始查询用户信息
        System.out.println("----------校验完成，开始查询用户信息-----------");
        SysUser sysUser = null;
        try {
            //开始查询用户信息
            sysUser= loginService.queryByLoginName(loginName);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("-------查询失败--------");
            return "../../index";
        }
        //控制台查看查询到的用户信息
        System.out.println("----------查询成功--------------");
        System.out.println("sysUser------"+sysUser);
        //用户不存在
        if(sysUser==null) {
            model.addAttribute("msg", "用户不存在，请确认!");
            return "../../index";
        }
        //密码错误
        if(!MD5Util.encode(loginPassword).equals(sysUser.getLoginPwd())) {
            model.addAttribute("msg", "密码错误!");
            return "../../index";
        }


        LoginObject loginObj = new LoginObject();
        loginObj.setUserId(sysUser.getUserId());
        loginObj.setUserName(sysUser.getUserName());
        loginObj.setIdentity(sysUser.getIdentity());
        loginObj.setLoginPwd(sysUser.getLoginPwd());

        //将用户身份信息保存在session中
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_USER_KEY, loginObj);
        //使用model传回前台数据，会自动放到session域中
//        model.addAttribute(SESSION_USER_KEY,loginObj);


/*        //查询用户所有的页面按钮权限,并且放到会话当中
        Map<String,String> rightsMap = sysUserService.queryUserRights(sysUser.getUserId());
        session.setAttribute(USER_POPEDOM_KEY, rightsMap);*/


        //当设置完成权限之后，在线的用户权限自动刷新
        //获取ServletContext
//        ServletContext application = session.getServletContext();
//        application.setAttribute(String.valueOf(sysUser.getUserId()), session);


        //登录完成 查询菜单 处理拦截器问题
        return "main";
    }

    /**
     * 输出验证码
     * @param request
     * @param response
     */
    @GetMapping("verify")
    public void verifyCode(HttpServletRequest request,
                           HttpServletResponse response) {
        VerifyCode.exportImg(request, response, 120, 50);
    }

    /**
     * 查询系统菜单信息
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("queryMenu")
    public Map<String,Object> queryMenu(HttpServletRequest request) throws Exception{
        LoginObject loginObject = getLoginObject(request);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("userId", loginObject.getUserId());//用户id
        map.put("lev", 1);//菜单层级
        map.put("identity", loginObject.getIdentity());

        System.out.println("用户的权限identity---------"+map.get("identity"));

        List<Map<String,Object>> list = loginService.queryMenu(map);

        Map<String,Object> listMap = new HashMap<String, Object>();
        listMap.put("list", list);

        Map<String,Object> returnMap = new HashMap<String, Object>();
        returnMap.put("data", listMap);
        returnMap.put("status", "200");
        return returnMap;
    }

    /**
     * 注销
     * @param session
     * @return
     */
    @RequestMapping("logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "../../index";
    }

    /**
     * 到修改密码页面
     * @return
     */
    @RequestMapping("updPassword")
    public String toUpdPassword() {
        return "login/updPassword";
    }

    /**
     * 到用户管理首页
     * @return
     */
    @RequestMapping("queryUser")
    public String toQueryUser() {
        return "sysuser/index";
    }

    @RequestMapping("fabuxiangmu")
    public String fabuxiangmu(){
        return "item";
    }
}